package com.ywu.bpmn.standard.listener;

import com.ywu.bpmn.spi.dto.YwuBpmnMqDto;
import com.ywu.bpmn.standard.produce.YwuBpmnProduce;
import com.ywu.common.gson.GsonUtils;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.IdentityLink;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @ClassName EnterUserTaskListener
 * @Description TODO
 * @Author GroundDemo
 * @Date 2025/4/23 11:35
 * @Version 1.0
 **/
@Component
public class YwuCreateUserTaskListener implements TaskListener {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private YwuBpmnProduce produce;

    @Override
    public void notify(DelegateTask delegateTask) {
        Object instanceId = delegateTask.getVariable("instanceId");
        // 发送MQ
        YwuBpmnMqDto ywuBpmnMqDto = new YwuBpmnMqDto();
        ywuBpmnMqDto.setNodeId(delegateTask.getTaskDefinitionKey());
        ywuBpmnMqDto.setInstanceId((String) instanceId);
        ywuBpmnMqDto.setTaskId(delegateTask.getId());
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(delegateTask.getProcessDefinitionId()).singleResult();
        ywuBpmnMqDto.setKey(processDefinition.getKey());
        ywuBpmnMqDto.setBpmnInstanceId(delegateTask.getProcessInstanceId());
        if (delegateTask.getAssignee() != null) {
            ywuBpmnMqDto.setAssignee(delegateTask.getAssignee());
        } else {
            Set<IdentityLink> candidates = delegateTask.getCandidates();
            StringBuilder resAssignee = new StringBuilder();
            for (IdentityLink candidate : candidates) {
                resAssignee.append(candidate.getUserId());
            }
            ywuBpmnMqDto.setAssignee(String.join(",", resAssignee));
        }
        produce.setKey("task-create");
        produce.produce(GsonUtils.serialize(ywuBpmnMqDto));
    }
}
